package utilities;



import java.io.BufferedWriter;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import java.lang.reflect.*;

public class CommandProcessor extends Processor {


	public CommandProcessor()
	{
	}
	
	public CommandProcessor(String name, BufferedWriter log, List actionList,
			Object configData, int sleeps) {		
		super(name, log, actionList, configData, sleeps);
	}

	
	private void processKey(String key)
	{						

		
		if(key==null) return;		
		if(key.equals("No command found")) return;
		
		//you may have a set of variables in this key, the first is the filter key
		//String vars[] = key.split("/\?/",2);
		
		String q = Pattern.quote("?");
		String vars[] = key.split(q,2);
		try {
			log.write("tried split " + vars[0] + "\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		KeyActions pf = pc.getFilterByName(vars[0]);
		if(pf!=null)
		{
			for(Iterator it = pf.getActions().iterator();it.hasNext();)
			{
				if(vars.length==1)
				{
					servers.Dragon.delgator((ProcFilter)it.next(),null);				
				}
				else
				{
					servers.Dragon.delgator((ProcFilter)it.next(),vars[1]);										
				}
			}
		}

	}
	
	public void run()
	{
		try
		{
        String key;
		active = true;
		int actSize = 0;
		while(running)
			{
				if(active)
				{
					//get all actions available, process each one
					actSize =workQueue.size();
					for(int i=0; i< actSize;i++)
					{
						//process each action
						 key = workQueue.get(i).toString();
						 
						 //log.write("Processing key: " + key + "\n");
						 
						 processKey(key);						
					}
					for(int i=0; i< actSize;i++)
					{
						//remove action
						workQueue.remove(0);
					}					
				}	
			this.sleep(sleeps);
	
			
			}
		}
		catch(Exception e)
		{
			try
			{
			log.write("Thread died: " + name + "\n" + e.getMessage());
			}catch(Exception ee) {}
		}
	}
	
}
